from typing import Sequence

from src.application.order.dto.order import OrderDTO
from src.application.order.interfaces import OrderReader
from src.application.user.interfaces.reader import GetUsersFilters
from src.domain.common.constants import Empty, OrderBy


class OrderReaderMock(OrderReader):
    def __init__(self):
        self.order: dict[int, OrderDTO] = {}

    async def get_order_by_id(self, order_id: int) -> OrderDTO:
        if order_id not in self.order:
            raise UserIdNotExist(order_id)

        user = self.users[user_tg_id]
        return user

    async def get_users(self, filters: GetUsersFilters) -> list[dto.UserDTOs]:
        users = list(self.users.values())
        if filters.is_registered is not Empty.UNSET:
            users = [user for user in users if user.is_registered == filters.is_registered]
        if filters.order == OrderBy.ASC:
            users.sort(key=lambda user: user.tg_id)
        else:
            users.sort(key=lambda user: user.tg_id, reverse=True)

        offset = filters.offset if filters.offset is not Empty.UNSET else 0
        limit = filters.limit if filters.limit is not Empty.UNSET else len(users)
        last_index = offset + limit
        users = users[offset:last_index]
        return users

    async def add_user(self, user: dto.UserDTO) -> None:
        self.users[user.tg_id] = user

    async def add_users(self, users: Sequence[dto.UserDTOs]) -> None:
        for user in users:
            await self.add_user(user)
